﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Collections;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using BONSAI.Common.Enum;
using BONSAI.Common.DTO;

namespace BONSAI.Common
{
    public class BONSAIUtils
    {
        #region Email
        public static bool IsValidEmail(string email)
        {
            if (string.IsNullOrEmpty(email))
                return false;

            email = email.Trim();
            if (email.IndexOf(" ") >= 0)
                return false;

            var match = Regex.Match(email, GetEmailPattern(), RegexOptions.IgnoreCase);

            var isValid = match.Success;

            return isValid;
        }

        private static string GetEmailPattern()
        {
            return Convert.ToString(ConfigurationSettings.AppSettings["EmailPattern"]);

        }
        #endregion

        #region Send Email
        public class EmailUtil
        {
            public static void SendContactMail(ContactMailInfo mail)
            {
                var objMail = new EmailPacket { To = mail.EmailTo, EmailTemplate = mail.EmailTemplate };

                //Add fixed parameters to EmailTemplate(*.xslt)
                var objParams = new Hashtable
                                    {
                                        {"CompanyName", mail.SystemDisplayName},
                                        {"CustomerName", mail.Name},
                                        {"CustomerEmail", mail.Email},
                                        {"CustomerContactTitle", mail.Subject},
                                        {"Content", mail.Message},
                                    };

                if (!string.Empty.Equals(objMail.To))
                {
                    objMail.SendEmail(objParams, SendMailTypeEnum.SEND_CONTACTUS_EMAIL);
                }
            }
            public static void SendOrderMail(OrderMailInfo mail)
            {
                var objMail = new EmailPacket { To = mail.EmailTo, EmailTemplate = mail.EmailTemplate };

                //Add fixed parameters to EmailTemplate(*.xslt)
                var objParams = new Hashtable
                                    {
                                        {"OrderId", mail.OrderId},
                                        {"CompanyName", mail.SystemDisplayName},
                                        {"CustomerName", mail.Name},
                                        {"Address", mail.Address},
                                        {"TelPhone", mail.Tel},
                                        {"product", mail.Product},
                                        {"Content", mail.Message},
                                    };

                if (!string.Empty.Equals(objMail.To))
                {
                    objMail.SendEmail(objParams, SendMailTypeEnum.SEND_CONTACTUS_EMAIL);
                }
            }
        }
           
        #endregion

        #region Image utilities
        public class ImageUtil
        {
            /// <summary>
            /// method : CreateThumbnailAndPreviewToJPG
            /// Image formats : JPG,JPEG,JPE,BMP,PNG,GIF,TIFF,TIF
            /// author : LinhVM
            /// Creation date : 28.Jul.2009
            /// </summary>
            /// <param name="originalBMP"></param>
            /// <param name="destinationPath"></param>
            /// <param name="imageTypeEnum"></param>
            private static void CreateThumbnailAndPreviewToJPG(Bitmap originalBMP, string destinationPath, ImageTypeEnum imageTypeEnum, UploadImageEnum uploadImageEnum)
            {
                try
                {
                    //Get new size for image
                    int newWidth = 0;
                    int newHeight = 0;

                    // get siez for thumnail or preview
                    if (ImageTypeEnum.IMAGE_THUMBNAIL.Equals(imageTypeEnum))
                    {
                        GetSizeForImageThumbnail(ref newHeight, ref newWidth);

                        switch (uploadImageEnum)
                        {
                            case UploadImageEnum.MINI_IMAGE:
                                newHeight = 50;
                                newWidth = (newHeight * originalBMP.Width) / originalBMP.Height;
                                break;
                            case UploadImageEnum.FULL_IMAGE:
                                newHeight = 95;
                                newWidth = (newHeight * originalBMP.Width) / originalBMP.Height;
                                break;
                            case UploadImageEnum.PORT_IMAGE:
                                newHeight = 78;
                                newWidth = 49;
                                break;
                            case UploadImageEnum.CLIENT_SITUATION:
                                newHeight = 56;
                                newWidth = 192;
                                break;
                            case UploadImageEnum.PRODUCTTYPE_IMAGE:
                                newHeight = 208;
                                newWidth = 910;
                                break;
                            case UploadImageEnum.ARTICLE_IMAGE:
                                newHeight = 131;
                                newWidth = 184;
                                break;
                            case UploadImageEnum.PRODUCT_IMAGE:
                                newWidth = 312;// 3/2
                                newHeight = (newWidth * originalBMP.Height) / originalBMP.Width; ;//250;// 3/2
                                break;
                            case UploadImageEnum.FACTORY_IMAGE:
                                newHeight = 95;
                                newWidth = (newHeight * originalBMP.Width) / originalBMP.Height;
                                break;
                            case UploadImageEnum.PARTNER:
                                newWidth = 174;
                                newHeight = 108;
                                break;
                            case UploadImageEnum.MARKETING:
                                newWidth = 178;
                                newHeight = 90;
                                break;
                            case UploadImageEnum.NEWS_ADD:
                                newWidth = 211;
                                newHeight = 124;
                                break;

                        }
                    }
                    else
                    {
                        if (ImageTypeEnum.IMAGE_PREVIEW.Equals(imageTypeEnum))
                        {
                            GetSizeForImagePreview(ref newHeight, ref newWidth);

                            switch (uploadImageEnum)
                            {
                                case UploadImageEnum.MINI_IMAGE:
                                    newWidth = 307;
                                    newHeight = 373;
                                    break;
                                case UploadImageEnum.FULL_IMAGE:
                                    newWidth = 959;
                                    newHeight = 332;
                                    break;
                                case UploadImageEnum.PORT_IMAGE:
                                    newWidth = originalBMP.Width;
                                    newHeight = originalBMP.Height;
                                    break;
                                case UploadImageEnum.CLIENT_SITUATION:
                                    newWidth = originalBMP.Width;
                                    newHeight = originalBMP.Height;
                                    break;
                                case UploadImageEnum.PRODUCT_IMAGE:
                                    if (originalBMP.Width <= 190)
                                    {
                                        newWidth = originalBMP.Width;
                                        newHeight = originalBMP.Height;
                                    }
                                    else
                                    {
                                        if (originalBMP.Width - originalBMP.Height > 16)
                                        {
                                            newWidth = 190; //169
                                            newHeight = (newWidth * originalBMP.Height) / originalBMP.Width; //129
                                        }
                                        else
                                        {
                                            newHeight = 175;
                                            newWidth = (newHeight * originalBMP.Width) / originalBMP.Height; //129
                                        }
                                    }
                                    break;
                                case UploadImageEnum.FACTORY_IMAGE:
                                    newWidth = 923;
                                    newHeight = 352;
                                    break;
                                case UploadImageEnum.PRODUCTTYPE_IMAGE:
                                    newHeight = 208;
                                    newWidth = 910;
                                    break;
                                case UploadImageEnum.PARTNER:
                                    newWidth = originalBMP.Width;
                                    newHeight = originalBMP.Height;
                                    break;
                                case UploadImageEnum.MARKETING:
                                    newWidth = originalBMP.Width;
                                    newHeight = originalBMP.Height;
                                    break;
                                case UploadImageEnum.NEWS_ADD:
                                    newWidth = 430;
                                    newHeight = 292;
                                    break;

                            }
                        }
                    }

                    switch (uploadImageEnum)
                    {
                        case UploadImageEnum.BRANCH_IMAGE:
                            newWidth = 576;
                            newHeight = 147;
                            break;
                        case UploadImageEnum.MAP_IMAGE:
                            newWidth = 1024;
                            newHeight = 768;
                            break;
                        case UploadImageEnum.CLIENT_LOGO:
                            newWidth = 183;
                            newHeight = 114;
                            break;
                    }

                    // Create a new bitmap which will hold the previous resized bitmap
                    var newBMP = new Bitmap(originalBMP, newWidth, newHeight);

                    // Create a graphic based on the new bitmap
                    Graphics oGraphics = Graphics.FromImage(newBMP);

                    // Set the properties for the new graphic file
                    oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
                    oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    // Draw the new graphic based on the resized bitmap
                    oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

                    // Save the new graphic file to the server
                    newBMP.Save(destinationPath, ImageFormat.Jpeg);

                    // clean up
                    newBMP.Dispose();
                    oGraphics.Dispose();
                }
                catch (Exception ex)
                {
                    ex.ToString();
                }
            }

            public static void GetSizeForImageThumbnail(ref int height, ref int width)
            {
                try
                {
                    width = Convert.ToInt32(ConfigurationSettings.AppSettings[BONSAIConstants.THUMBNAIL_WIDTH_TEXT].ToString());
                    height = Convert.ToInt32(ConfigurationSettings.AppSettings[BONSAIConstants.THUMBNAIL_HEIGHT_TEXT].ToString());
                }
                catch
                {
                    width = BONSAIConstants.THUMBNAIL_WIDTH;
                    height = BONSAIConstants.THUMBNAIL_HEIGHT;
                }
            }

            public static void GetSizeForImagePreview(ref int height, ref int width)
            {
                try
                {
                    width = Convert.ToInt32(ConfigurationSettings.AppSettings[BONSAIConstants.PREVIEW_WIDTH_TEXT].ToString());
                    height = Convert.ToInt32(ConfigurationSettings.AppSettings[BONSAIConstants.PREVIEW_HEIGHT_TEXT].ToString());
                }
                catch
                {
                    width = BONSAIConstants.PREVIEW_WIDTH;
                    height = BONSAIConstants.PREVIEW_HEIGHT;
                }
            }

            public static int DoImageTasks(Bitmap originalBMP, string serverMapPath, string relativePhotos, ref string relativeImageUrl, ref string relativePreviewUrl, UploadImageEnum uploadImageEnum, string preFileName)
            {
                try
                {
                    // get ID for name of image
                    string id = preFileName + Guid.NewGuid().ToString().ToLower();

                    // 1. for make thumbnail
                    // "update about me" do not make thumbnail
                    if (!UploadImageEnum.ABOUTME_UPDATE.Equals(uploadImageEnum))
                    {
                        // get destination path for thubnail image
                        string destThumnailPath = CreateImagePathFromServerMapPath(serverMapPath,
                                                                                   ImageTypeEnum.IMAGE_THUMBNAIL, id);

                        // make thumbnail
                        CreateThumbnailAndPreviewToJPG(originalBMP, destThumnailPath, ImageTypeEnum.IMAGE_THUMBNAIL, uploadImageEnum);

                        // get relativeImageUrl
                        relativeImageUrl = GetRelativeImageUrl(destThumnailPath, relativePhotos);
                    }

                    //2. for make preview
                    // get destination path for preview image
                    string destPreviewPath = CreateImagePathFromServerMapPath(serverMapPath, ImageTypeEnum.IMAGE_PREVIEW, id);

                    // make preview
                    CreateThumbnailAndPreviewToJPG(originalBMP, destPreviewPath, ImageTypeEnum.IMAGE_PREVIEW, uploadImageEnum);

                    // get relativeImageUrl
                    relativePreviewUrl = GetRelativeImageUrl(destPreviewPath, relativePhotos);
                }
                catch
                {
                    return 0;
                }

                // clean up
                originalBMP.Dispose();

                return 1;
            }

            private static string GetRelativeImageUrl(string destThumnailPath, string relativePhotos)
            {
                // get relativeImageUrl
                var param = new char[2];
                param[0] = Convert.ToChar(@"\");
                param[1] = '/';

                int i = destThumnailPath.LastIndexOfAny(param);

                string relativeImageUrl = relativePhotos + destThumnailPath.Substring(i + 1);
                return relativeImageUrl;
            }

            private static string CreateImagePathFromServerMapPath(string serverMapPath, ImageTypeEnum imageTypeEnum, string id)
            {
                // creat image path
                string imageViewType = (ImageTypeEnum.IMAGE_THUMBNAIL.Equals(imageTypeEnum)) ? BONSAIConstants.IMAGE_VIEW_TYPE.THUMBNAIL : BONSAIConstants.IMAGE_VIEW_TYPE.PREVIEW;
                string imageName = id + imageViewType;
                string destinationPath = serverMapPath + "\\" + imageName + BONSAIConstants.JPG;

                return destinationPath;
            }

            public static void ClearOldImageOnServer(string serverMapPath, string relativeUrl)
            {
                try
                {
                    if (string.IsNullOrEmpty(serverMapPath) || string.IsNullOrEmpty(relativeUrl))
                    {
                        return;
                    }

                    // get full file path of image on server to clear
                    string imageName = serverMapPath + GetImageNameFromFilePath(relativeUrl);

                    // clear this file
                    File.Delete(imageName);
                }
                catch (Exception ex)
                {
                    // on resume
                }
            }

            public static string GetImageNameFromFilePath(string filePath)
            {
                if (string.IsNullOrEmpty(filePath))
                {
                    return filePath;
                }

                var param = new char[2];
                param[0] = Convert.ToChar(@"\");
                param[1] = '/';

                int i = filePath.LastIndexOfAny(param);
                string name = filePath.Substring(i + 1);

                return name;
            }
        }
        #endregion Image utilities

        #region Download
        public static void DownLoadFile(HttpResponse Response, HttpRequest Request, string url)
        {
            //download
            try
            {
                if (!File.Exists(url)) return;
                var file = new FileInfo(url);

                Response.Clear();

                string browse = Request.Browser.Type;

                // get 2 characters 
                string ie = browse.Substring(0, 2);

                string filename;

                // IE
                if ("IE".Equals(ie.ToUpper()))
                {
                    filename = HttpUtility.UrlPathEncode(file.Name);
                }
                // Fire Fox
                else if ("FI".Equals(ie.ToUpper()))
                {
                    filename = HttpUtility.HtmlAttributeEncode(file.Name);

                    filename = filename.Replace(' ', '_');
                }
                // Safari,...
                else
                {
                    filename = file.Name;

                    // filename = filename.Replace(' ', '_');
                }

                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                //Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

                Response.AddHeader("Content-Length", file.Length.ToString());

                Response.ContentType = "application/octet-stream";
                //Response.ContentType = "application/x-cdf";

                Response.WriteFile(url);

                Response.Flush();

                Response.End();
            }
            catch (ThreadAbortException ex2)
            {

            }

        }

        #endregion

        #region Public methods
        
        public static bool IsNumber(string str)
        {
            try
            {
                Convert.ToDouble(str);
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        public static string MD5(string password)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("x");
                    else
                        ret += a.ToString("x");
                }
                return ret;
            }
            catch
            {
                throw;
            }
        }

        public static bool IsValidUsername(string username)
        {
            // check null or empty
            if (string.IsNullOrEmpty(username))
            {
                return false;
            }

            // check min length
            int usernameMinLength = Convert.ToInt32(ConfigurationSettings.AppSettings[BONSAIConstants.USERNAME_MINLENGTH]);
            if (username.Length < usernameMinLength)
            {
                return false;
            }

            // check special chars
            foreach (char c in BONSAIConstants.InvalidCharArray)
            {
                // if username string contains a special char
                if (username.Contains(c))
                {
                    return false;
                }
            }

            // username is valid
            return true;
        }

       public static string DecodeForSendAutoMail(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }

            text = text.Replace("&lt;br /&gt;", "<br />");
            text = text.Replace("&lt;b&gt;", "<b>");
            text = text.Replace("&lt;/b&gt;", "</b>");
            text = text.Replace("&lt;img", "<img");
            text = text.Replace("/&gt;", "/>");

            return text;
        }
        /// <summary>
        /// Decode for OrderEmail
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string DecodeForSendOrderMail(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }


            text = text.Replace("&lt;table  border=" + 1 + "&gt;", "<table  border=" + 1 + ">");
            text = text.Replace("&lt;tr&gt;", "<tr>");
            text = text.Replace("&lt;td&gt;", "<td>");
            text = text.Replace("&lt;/table&gt;", "</table>");
            text = text.Replace("&lt;/tr&gt;", "</tr>");
            text = text.Replace("&lt;/td&gt;", "</td>");
            text = text.Replace("&lt;td colspan=" + "4" + " Align=" + "right" + "&gt;", "<td colspan=" + 4 + " Align=" + "right" + ">");


            return text;
        }

        public static string EncodeNewLineForward(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }

            text = text.Replace("\r\n", "<br />");

            return text;
        }

        public static string EncodeNewLineBackward(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }

            text = text.Replace("<br />", "\r\n");

            return text;
        }

        public static string CutBeginCharOfUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return url;
            }

            int i = url.IndexOf("/");

            return url.Substring(i, url.Length - 1);
        }

        //public static bool IsAdmin(LoginInfo loginInfo)
        //{
        //    // only enter here if login ok and session is not timeout yet

        //    if (EPROConstants.ADMIN.Trim().ToLower().Equals(loginInfo.accountDTO.Username.Trim().ToLower()))
        //    {
        //        return true;
        //    }

        //    return false;
        //}

        public static string ConvertDMYtoMDYstring(string DMY)
        {

            string MDY = string.Empty;

            // split string DMY
            string[] arr = DMY.Split('/');

            // convert to DMY
            MDY = arr[1] + "/" + arr[0] + "/" + arr[2];

            return MDY;
        }
        public static string ConvertDMYhhmmsstoMDYhhmmssstring(DateTime DMY)
        {

            string MDY = string.Empty;
            string DD = string.Empty;
            string MM = string.Empty;
            string YY = string.Empty;
            string h = string.Empty;
            string m = string.Empty;
            string s = string.Empty;

            DD = DMY.Day.ToString();
            MM = DMY.Month.ToString();
            YY = DMY.Year.ToString();
            h = DMY.Hour.ToString();
            m = DMY.Minute.ToString();
            s = DMY.Second.ToString();



            // convert to DMY
            MDY = DD + "/" + MM + "/" + YY + " " + h + ":" + m + ":" + s;

            return MDY;
        }

        /// <summary>
        /// method : 
        /// author : QuyenTV
        /// description : change date from mdy to dmy
        /// Creation date : 
        /// </summary>
        /// <param name="MDY"></param>
        /// <returns></returns>
        public static string ConvertMDYtoDMYstring(string MDY)
        {

            string DMY = string.Empty;

            // split string MDY
            string[] arr = MDY.Split('/');

            // convert to MDY
            DMY = arr[1] + "/" + arr[0] + "/" + arr[2];

            return DMY;
        }
        public static string GetUrlForCheckImageExist(string imageUrl)
        {
            if (string.IsNullOrEmpty(imageUrl))
            {
                return imageUrl;
            }

            var param = new char[2];
            param[0] = Convert.ToChar(@"\");
            param[1] = '/';

            int i = imageUrl.LastIndexOfAny(param);

            string resultUrl = imageUrl.Substring(i + 1);
            return resultUrl;

        }


        public static bool IsLangClickEvent(string request)
        {
            if (request == null)
            {
                return false;
            }

            if (request.EndsWith(BONSAIConstants.LANG_VN) || request.EndsWith(BONSAIConstants.LANG_EN))
            {
                return true;
            }

            return false;
        }

        public static string FixImageUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return string.Empty;
            }

            return url.Substring(3);
        }

        public static string GetUrlToCheckImageExist(string imageUrl)
        {
            if (string.IsNullOrEmpty(imageUrl))
            {
                return imageUrl;
            }

            var param = new char[2];
            param[0] = Convert.ToChar(@"\");
            param[1] = '/';

            int i = imageUrl.LastIndexOfAny(param);

            string resultUrl = imageUrl.Substring(i + 1);
            return resultUrl;

        }

        public static string GetFileName(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return string.Empty;
            }

            int i = filename.LastIndexOf('.');

            return filename.Substring(0, i);
        }

        public static string GetFileExt(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return string.Empty;
            }

            int i = filename.LastIndexOf('.');

            return filename.Substring(i);
        }

        #endregion Public methods


        public static string Image_Substring(string str)
        {
            
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Substring(3);
            }
            return str;
        }



        public static string PriceVni(double price, double rate)
        {

            if (price != 0)
            {
                return Math.Round(price*rate).ToString("#,###.###");
            }
            return null;
        }

        //convert
        public static string ConvertToUnSign(string text)
        {

            for (var i = 33; i < 48; i++)
            {

                text = text.Replace(((char) i).ToString(), "");

            }

            for (var i = 58; i < 65; i++)
            {

                text = text.Replace(((char) i).ToString(), "");

            }

            for (var i = 91; i < 97; i++)
            {

                text = text.Replace(((char) i).ToString(), "");

            }

            for (var i = 123; i < 127; i++)
            {

                text = text.Replace(((char) i).ToString(), "");

            }

            text = text.Replace(" ", "-");

            var regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");

            var strFormD = text.Normalize(System.Text.NormalizationForm.FormD);

            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');

        }
        public static string SubString(string str, int lenght)
        {
            if (str.Length < lenght || string.IsNullOrEmpty(str)) return str;

            string tmp = str.Substring(0, lenght);
            int index = tmp.LastIndexOf(' ');

            if (index > 1)
            {
                tmp = tmp.Substring(0, index);
            }

            return tmp + " ...";
        }

    }
}
